/*
 Xern Entity Relocation Network
 Copyright (C) 2010-2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include "Xern/Exceptions.hpp"
#include "Xern/Engine.hpp"
#include "Xern/PluginRegistrator.hpp"
#include "Xern/ResourceManager.hpp"
#include "OpenALSound.hpp"
#include "Listener.hpp"
#include "Source.hpp"
#include "SoundLoader.hpp"

namespace XernAL
{
	static PluginRegistrator<OpenALSound> openALSoundPlugin("Sound", "OpenAL");
	OpenALSound::OpenALSound()
	{
		context = NULL;
		nosound = false;
	}

	OpenALSound::~OpenALSound()
	{
	}

	bool OpenALSound::IsNoSound() const
	{
		return nosound;
	}

	void OpenALSound::Initialize()
	{
		if(context)
			return;

		// Read the nosound flag.
		nosound = Engine::Get().GetSystemDescription().nosound;

		// Open the device.
		device = alcOpenDevice(NULL);
		if(!device)
			throw XernException("Failed to open an OpenAL device.");

		// Create the OpenAL context.
		context = alcCreateContext(device, NULL);
		if(!context)
			throw XernException("Failed to create OpenAL context.");

		// Set the current context.
		alcMakeContextCurrent(context);

		// Create the sound cache.
		soundCache.reset(new SoundCache());

		// Create the sound loader.
		soundLoader.reset(new SoundLoader());
		Engine::Get().GetResourceManager()->RegisterResourceLoader(soundLoader);
	}

	void OpenALSound::Shutdown()
	{
		if(!context)
			return;

		// Destroy the sound loader
		Engine::Get().GetResourceManager()->UnregisterResourceLoader(soundLoader);
		soundLoader.reset();

		// Destroy the sound cache.
		soundCache.reset();

		// Destroy the context.
		alcMakeContextCurrent(NULL);
		alcDestroyContext(context);
		context = NULL;

		// Close the device
		alcCloseDevice(device);
		device = NULL;
	}

	bool OpenALSound::Frame(float delta)
	{
		// Ignore if not sound.
		if(nosound)
			return true;

		// Update the listener.
		if(currentListener)
			currentListener->Update(delta);

		// Update all of the sources.
		Sources::iterator it = sources.begin();
		while(it != sources.end())
		{
			// Get the source
			boost::shared_ptr<Source> source = it->lock();
			if(source)
			{
				// Update the source.
				source->Frame(delta);
				it++;
			}
			else
			{
				// Remove the deleted source from the list.
				sources.erase(it++);
			}
		}

		return true;
	}

	boost::shared_ptr<ISoundListener>
	OpenALSound::CreateListener()
	{
		boost::shared_ptr<ISoundListener> ret (new Listener());
		return ret;
	}

	boost::shared_ptr<ISoundSource>
	OpenALSound::CreateSource()
	{
		// Create the source.
		boost::shared_ptr<Source> ret (new Source(soundCache));

		// Register the source.
		sources.push_back(ret);
		Engine::Get().GetResourceManager()->RegisterExternalResource(ret);

		// Return the source.
		return ret;
	}

	void OpenALSound::SetCurrentListener(boost::shared_ptr<ISoundListener> listener)
	{
		boost::shared_ptr<Listener> alListener =
				boost::dynamic_pointer_cast<Listener> (listener);
		if(!alListener)
			throw XernException("Expected an OpenAL listener.");

		currentListener = alListener;
	}

	boost::shared_ptr<ISoundListener> OpenALSound::GetCurrentListener()
	{
		return currentListener;
	}

	boost::shared_ptr<const ISoundListener> OpenALSound::GetCurrentListener() const
	{
		return currentListener;
	}
};
